<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="mini"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="一级类目" prop="oneCategoryId">
        <el-select
          v-model="queryParams.oneCategoryId"
          @change="changeOne"
          placeholder="请选择"
        >
          <el-option label="请选择" :value="null"></el-option>
          <el-option
            v-for="(item, index) in categoryList1"
            :key="index"
            :label="item.categoryName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级类目" prop="twoCategoryId">
        <el-select
          v-model="queryParams.twoCategoryId"
          @change="changeTwo"
          placeholder="请选择"
        >
          <el-option label="请选择" :value="null"></el-option>
          <el-option
            v-for="(item, index) in categoryList2"
            :key="index"
            :label="item.categoryName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级类目" prop="threeCategoryId">
        <el-select v-model="queryParams.threeCategoryId" placeholder="请选择">
          <el-option label="请选择" :value="null"></el-option>
          <el-option
            v-for="(item, index) in categoryList3"
            :key="index"
            :label="item.categoryName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label-width="40" label="ID" prop="id">
        <el-input
          type="number"
          v-model="queryParams.id"
          placeholder="ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原料名称" prop="name">
        <el-input
          v-model.trim="queryParams.name"
          placeholder="请输入原料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:material:add']"
          >新增</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="materialList"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ backgroundColor: '#F7F8FA' }"
      height="380"
    >
      <el-table-column
        fixed="left"
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column width="55" label="ID" align="center" prop="id" />
      <el-table-column label="原料编号" align="center" prop="id" />
      <el-table-column
        label="原料名称"
        align="center"
        prop="name"
        show-overflow-tooltip
      />
      <el-table-column
        label="一级类目"
        align="center"
        prop="oneCategoryName"
        show-overflow-tooltip
      />
      <el-table-column
        label="二级类目"
        align="center"
        prop="twoCategoryName"
        show-overflow-tooltip
      />
      <el-table-column
        label="三级类目"
        align="center"
        prop="threeCategoryName"
        show-overflow-tooltip
      />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.status == '0'"
            @change="changeStatus(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        width="160px"
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:material:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:material:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品--原材料对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="①选择类目" name="1">
          <el-card>
            <el-form
              class="form-value"
              ref="form-left"
              :model="form"
              :rules="rules"
              label-position="top"
              label-width="80px"
              :disabled="editDisabled"
            >
              <el-row>
                <el-col :span="8">
                  <el-form-item label="一级类目:" prop="oneCategoryId">
                    <el-select
                      @change="formChangeOne"
                      v-model="form.oneCategoryId"
                      placeholder="请选择"
                      v-if="!editDisabled"
                    >
                      <el-option
                        v-for="(item, index) in formCategoryList1"
                        :key="index"
                        :label="item.categoryName"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                    <span v-else>{{ form.oneCategoryName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="二级类目:" prop="twoCategoryId">
                    <el-select
                      @change="formChangeTwo"
                      v-model="form.twoCategoryId"
                      placeholder="请选择"
                      v-if="!editDisabled"
                    >
                      <el-option
                        v-for="(item, index) in formCategoryList2"
                        :key="index"
                        :label="item.categoryName"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                    <span v-else>{{ form.twoCategoryName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="三级类目:" prop="threeCategoryId">
                    <el-select
                      @change="formChangeThree"
                      v-model="form.threeCategoryId"
                      placeholder="请选择"
                      v-if="!editDisabled"
                    >
                      <el-option
                        v-for="(item, index) in formCategoryList3"
                        :key="index"
                        :label="item.categoryName"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                    <span v-else>{{ form.threeCategoryName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
          <el-card style="margin-top: 10px">
            <el-form
              ref="form-type"
              :model="form"
              :rules="rules"
              label-position="top"
              label-width="100px"
              :disabled="editDisabled"
            >
              <el-form-item label="选择表单:" prop="type">
                <el-select
                  v-model="form.type"
                  placeholder="请选择"
                  v-if="!editDisabled"
                >
                  <el-option label="水泥" value="1"></el-option>
                  <el-option label="粉煤灰" value="2"></el-option>
                  <el-option label="矿粉" value="3"></el-option>
                  <el-option label="硅灰" value="4"></el-option>
                  <el-option label="石灰石粉" value="5"></el-option>
                  <el-option label="混凝土外加剂" value="6"></el-option>
                  <el-option label="膨胀剂" value="7"></el-option>
                  <el-option label="湿拌砂浆稳塑剂" value="8"></el-option>
                  <el-option label="合成纤维" value="9"></el-option>
                  <el-option label="砂" value="10"></el-option>
                  <el-option label="卵石/破碎石/轻集料" value="11"></el-option>
                  <el-option label="其他" value="99"></el-option>
                </el-select>
                <span v-else>{{ computedType(form.type) }}</span>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="②填写信息" name="2" v-if="form.type">
          <el-form
            ref="form-right"
            :model="formContent"
            label-width="250px"
            label-position="right"
            :disabled="editDisabled"
          >
            <el-card>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    :rules="[
                      { required: true, message: '请填写原料名称', trigger: 'blur' },
                    ]"
                    label="原料名称:"
                    prop="name"
                  >
                    <el-input
                      v-model="formContent.name"
                      placeholder="请输入原料名称"
                      v-if="!editDisabled"
                    />
                    <span v-else>{{
                      formContent.name ? formContent.name : "——"
                    }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    :rules="[
                      { required: true, message: '请选择', trigger: 'blur' },
                    ]"
                    label="状态:"
                    prop="status"
                  >
                    <el-switch
                      v-model="formContent.status"
                      :active-value="0"
                      :inactive-value="1"
                      v-if="!editDisabled"
                    />
                    <span v-else>{{
                      formContent.status == 0 ? "启用" : "关闭"
                    }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row
                v-for="(formArr, index) in formData.requiredArr"
                :key="index"
              >
                <el-col :span="12">
                  <el-form-item
                    :rules="[
                      {
                        required: formArr[0].required,
                        message: '请填写' + formArr[0].label,
                        trigger: 'blur',
                      },
                      { validator: formArr[0].validatorNumber ? validatorNumber : '', trigger: 'blur' },
                    ]"
                    :label="formArr[0].label + ':'"
                    :prop="formArr[0].key"
                  >
                    <el-input
                      v-model="formContent[formArr[0].key]"
                      :placeholder="formArr[0].placeholder"
                      v-if="!editDisabled"
                    />
                    <span v-else>{{
                      formContent[formArr[0].key]
                        ? formContent[formArr[0].key]
                        : "——"
                    }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="formArr[1]">
                  <el-form-item
                    :rules="[
                      {
                        required: formArr[1].required,
                        message: '请填写' + formArr[1].label,
                        trigger: 'blur',
                      },
                      { validator: formArr[1].validatorNumber ? validatorNumber : '', trigger: 'blur' },
                    ]"
                    :label="formArr[1].label + ':'"
                    :prop="formArr[1].key"
                  >
                    <el-input
                      v-model="formContent[formArr[1].key]"
                      :placeholder="formArr[1].placeholder"
                      v-if="!editDisabled"
                    />
                    <span v-else>{{
                      formContent[formArr[1].key]
                        ? formContent[formArr[1].key]
                        : "——"
                    }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            <el-card style="margin-top: 10px">
              <el-row>
                <el-col
                  :key="index"
                  v-for="(item, index) in formData.notRequiredArr"
                  :span="12"
                >
                  <el-form-item
                    :rules="[
                      {
                        required: item.required,
                        message: '请填写' + item.label,
                        trigger: 'blur',
                      },
                      { validator: item.validatorNumber ? validatorNumber : '', trigger: 'blur' },
                    ]"
                    :label="item.label + ':'"
                    :prop="item.key"
                  >
                    <el-input
                      v-model="formContent[item.key]"
                      :placeholder="item.placeholder"
                      v-if="!editDisabled"
                    />
                    <span v-else>{{
                      formContent[item.key] ? formContent[item.key] : "——"
                    }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            <el-card style="margin-top: 10px">
              <el-form-item label="备注:" prop="remark">
                <el-input
                  v-model="formContent.remark"
                  type="textarea"
                  placeholder="请输入内容"
                  v-if="!editDisabled"
                />
                <span v-else>{{
                  formContent.remark ? formContent.remark : "——"
                }}</span>
              </el-form-item>
            </el-card>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer" v-if="activeName == 1">
        <el-button type="primary" v-if="form.type" @click="activeName = '2'"
          >下一步</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-if="activeName == 2">
        <el-button @click="activeName = '1'">上一步</el-button>
        <el-button type="primary" @click="submitForm" v-if="!editDisabled"
          >提 交</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMaterial,
  getMaterial,
  delMaterial,
  addMaterial,
  updateMaterial,
} from "@/api/service/material";
import { listOnInfo, listInfo } from "@/api/service/info";
import form1 from "./form1";
import form2 from "./form2";
import form3 from "./form3";
import form4 from "./form4";
import form5 from "./form5";
import form6 from "./form6";
import form7 from "./form7";
import form8 from "./form8";
import form9 from "./form9";
import form10 from "./form10";
import form11 from "./form11";
import form99 from "./form99";
export default {
  name: "Material",
  data() {
    const validatorNumber = (rule, value, callback) => {
      console.log(rule);
      if (Object.is(Number(value), NaN)) {
        callback(new Error("请输入数字"));
      }
      if (+value < 0) {
        callback(new Error("不能为负数"));
      } else {
        callback();
      }
    }
    return {
      validatorNumber,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品--原材料表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        name: null,
        oneCategoryId: null,
        twoCategoryId: null,
        threeCategoryId: null,
      },
      // 表单参数
      form: {},
      formContent: {},

      form1,
      form2,
      form3,
      form4,
      form5,
      form6,
      form7,
      form8,
      form9,
      form10,
      form11,
      form99,

      // 表单校验
      rules: {
        oneCategoryId: [{ required: true, message: "请选择一级类目", trigger: "change" }],
        twoCategoryId: [{ required: true, message: "请选择二级类目", trigger: "change" }],
        threeCategoryId: [
          { required: true, message: "请选择三级类目", trigger: "change" },
        ],
        name: [
          { required: true, message: "原料名称不能为空", trigger: "blur" },
        ],
        type: [{ required: true, message: "请选择表单类型", trigger: "blur" }],
        status: [
          { required: true, message: "原料名称不能为空", trigger: "blur" },
        ],
        p1: [{ required: true, message: "必填字段1不能为空", trigger: "blur" }],
        p2: [{ required: true, message: "必填字段2不能为空", trigger: "blur" }],
        p3: [{ required: true, message: "必填字段3不能为空", trigger: "blur" }],
        p4: [{ required: true, message: "必填字段4不能为空", trigger: "blur" }],
      },

      activeName: "1",
      categoryList1: [],
      categoryList2: [],
      categoryList3: [],

      formCategoryList1: [],
      formCategoryList2: [],
      formCategoryList3: [],
      editDisabled: false,
    };
  },
  watch: {
    "form.type": {
      handler() {
        if (this.form.type) {
          const values = {
            name: null,
            status: 0,
            remark: null,
          };
          this["form" + this.form.type].requiredArr.forEach((item) => {
            values[item.key] = null;
          });
          this["form" + this.form.type].notRequiredArr.forEach((item) => {
            values[item.key] = null;
          });
          this.formContent = values;
        }
      },
    },
  },
  computed: {
    formData() {
      if (this.form.type) {
        return this["form" + this.form.type];
      } else {
        return {
          requiredArr: [],
          notRequiredArr: [],
        };
      }
    },
  },
  created() {
    this.getList();
    this.getListOnInfo();
  },
  methods: {
    // 开关
    changeStatus(item) {
      const form = { ...item };

      // 改变状态
      form.status = form.status == "0" ? 1 : 0;

      updateMaterial(form).then((response) => {
        this.$modal.msgSuccess("修改成功");
        item.status = form.status;
        //this.getList();
      });
    },
    changeOne() {
      this.queryParams.twoCategoryId = null;
      this.queryParams.threeCategoryId = null;
      this.categoryList2 = [];
      this.categoryList3 = [];
      if (!this.queryParams.oneCategoryId) {
        return;
      }
      listOnInfo({
        type: 2,
        oneCategoryId: this.queryParams.oneCategoryId,
      }).then((response) => {
        this.categoryList2 = response.data;
      });
    },
    changeTwo() {
      this.queryParams.threeCategoryId = null;
      this.categoryList3 = [];
      if (!this.queryParams.twoCategoryId) {
        return;
      }
      listOnInfo({
        type: 3,
        oneCategoryId: this.queryParams.oneCategoryId,
        twoCategoryId: this.queryParams.twoCategoryId,
      }).then((response) => {
        this.categoryList3 = response.data;
      });
    },
    formChangeOne() {
      this.form.twoCategoryId = null;
      this.form.threeCategoryId = null;
      this.formCategoryList2 = [];
      this.formCategoryList3 = [];
      if (!this.form.oneCategoryId) {
        return;
      }
      listOnInfo({ type: 2, oneCategoryId: this.form.oneCategoryId }).then(
        (response) => {
          this.formCategoryList2 = response.data;
        }
      );
    },
    formChangeTwo() {
      this.form.threeCategoryId = null;
      this.formCategoryList3 = [];
      if (!this.form.twoCategoryId) {
        return;
      }
      listOnInfo({
        type: 3,
        oneCategoryId: this.form.oneCategoryId,
        twoCategoryId: this.form.twoCategoryId,
      }).then((response) => {
        this.formCategoryList3 = response.data;
      });
    },
    formChangeThree() {
      this.form.categoryInfoId = this.formCategoryList3.find(
        (item) => item.id == this.form.threeCategoryId
      )?.categoryInfoId;
      // this.form.categoryInfoId = this.form.threeCategoryId;
    },
    // 查询 一级 二级 三级 目录数据
    getListOnInfo() {
      listOnInfo({ type: 1 }).then((res) => {
        this.categoryList1 = res.data;
        this.formCategoryList1 = res.data;
      });
    },
    /** 查询产品--原材料列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then((response) => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.editDisabled = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.activeName = "1";

      this.form = {
        id: null,
        type: null,
        name: null,
        oneCategoryId: null,
        twoCategoryId: null,
        threeCategoryId: null,
        categoryInfoId: null,
        p1: null,
        p2: null,
        p3: null,
        p4: null,
        m1: null,
        m2: null,
        status: 0,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增原材料";
    },
    /** 修改按钮操作 */
    handleUpdate(row, title = "修改原材料") {
      this.reset();
      const id = row.id || this.ids;
      getMaterial(id).then(async (response) => {
        this.form = response.data;

        listOnInfo({ type: 2, oneCategoryId: this.form.oneCategoryId }).then(
          (response) => {
            this.formCategoryList2 = response.data;
          }
        );
        listOnInfo({
          type: 3,
          oneCategoryId: this.form.oneCategoryId,
          twoCategoryId: this.form.twoCategoryId,
        }).then((response) => {
          this.formCategoryList3 = response.data;
        });

        await this.$nextTick();

        // this.formContent = JSON.parse(this.form.content)
        this.formContent = {
          ...JSON.parse(this.form.content),
          name: this.form.name,
          status: this.form.status,
          remark: this.form.remark,
        };

        this.open = true;
        this.title = title;
      });
    },
    handleClose() {
      this.editDisabled = false;
      this.cancel();
    },
    /** 详情按钮操作 */
    handleView(row) {
      this.editDisabled = true;
      this.handleUpdate(row, "查看原材料");
    },
    /** 提交按钮 */
    async submitForm() {
      try {
        await this.$refs["form-left"].validate();
      } catch (error) {
        this.activeName = "1";
        return;
      }
      await Promise.all([
        this.$refs["form-type"].validate(),
        this.$refs["form-right"].validate(),
      ]);

      this.form.name = this.formContent.name;
      this.form.status = this.formContent.status;
      this.form.remark = this.formContent.remark;
      this.form.content = JSON.stringify(this.formContent);
      if (this.form.id != null) {
        updateMaterial(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.resetQuery();
        });
      } else {
        addMaterial(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.resetQuery();
        });
      }

      // this.$refs["form-left"].validate(fvalid => {
      //     if (fvalid) {
      //         this.$refs["form-right"].validate(valid => {
      //             if (valid) {
      //                 if (this.form.id != null) {
      //                     updateMaterial(this.form).then(response => {
      //                     this.$modal.msgSuccess("修改成功");
      //                     this.open = false;
      //                     this.getList();
      //                     });
      //                 } else {
      //                     addMaterial(this.form).then(response => {
      //                     this.$modal.msgSuccess("新增成功");
      //                     this.open = false;
      //                     this.getList();
      //                     });
      //                 }
      //             }
      //         });
      //     }
      // })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除产品--原材料编号为"' + ids + '"的数据项？')
        .then(function () {
          return delMaterial(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/material/export",
        {
          ...this.queryParams,
        },
        `material_${new Date().getTime()}.xlsx`
      );
    },
    computedType(type) {
      switch (type) {
        case "1":
          return "水泥";
        case "2":
          return "粉煤灰";
        case "3":
          return "矿粉";
        case "4":
          return "硅灰";
        case "5":
          return "石灰石粉";
        case "6":
          return "混凝土外加剂";
        case "7":
          return "膨胀剂";
        case "8":
          return "湿拌砂浆稳塑剂";
        case "9":
          return "合成纤维";
        case "10":
          return "砂";
        case "11":
          return "卵石/破碎石/轻集料";
        case "99":
          return "其他";
        default:
          return "";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.edit-form {
  display: flex;
  .form-label {
    font-size: 14px;
    font-weight: bold;
    line-height: 36px;
    padding-right: 30px;
    .form-red {
      color: #d23c26;
    }
  }
  .form-value {
    display: flex;
    gap: 30px;
  }
}
::v-deep .el-tabs__content {
  max-height: 400px;
  overflow: auto;
}
</style>